import { useState, useRef } from 'react';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';

interface OCRUploaderProps {
  onProcessImage: (text: string, imagePreview: string) => void;
}

export function OCRUploader({ onProcessImage }: OCRUploaderProps) {
  const [isDragging, setIsDragging] = useState(false);
  const [isProcessing, setIsProcessing] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  // Mock OCR processing function
  const mockOCRProcessing = (): string => {
    // Simulate different types of text content
    const mockResults = [
      "这是一段模拟的OCR识别结果。这是一个在线OCR工具，可以将图片中的文字转换为可编辑的文本。",
      "Sample OCR recognition result. This is an online OCR tool that can convert text in images into editable text.",
      "123456789\nABCDEFGHIJKLMNOPQRSTUVWXYZ\nabcdefghijklmnopqrstuvwxyz",
      "OCR (Optical Character Recognition) 是一种将图像中的文字转换为可编辑文本的技术。\n\n这个工具使用先进的OCR算法来识别图片中的文字内容。"
    ];
    
    return mockResults[Math.floor(Math.random() * mockResults.length)];
  };
  
  const handleFile = (file: File) => {
    if (!file.type.startsWith('image/')) {
      toast.error('请上传图片文件');
      return;
    }
    
    // Display image preview
    const reader = new FileReader();
    reader.onload = (e) => {
      const previewUrl = e.target?.result as string;
      
      // Process image with mock OCR
      setIsProcessing(true);
      toast.info('正在识别图片中的文字...');
      
      // Simulate processing delay
      setTimeout(() => {
        const resultText = mockOCRProcessing();
        onProcessImage(resultText, previewUrl);
        setIsProcessing(false);
        toast.success('识别完成！');
      }, 2000);
    };
    reader.readAsDataURL(file);
  };
  
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };
  
  const handleDragLeave = () => {
    setIsDragging(false);
  };
  
  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFile(e.dataTransfer.files[0]);
    }
  };
  
  const handleClick = () => {
    fileInputRef.current?.click();
  };
  
  const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      handleFile(e.target.files[0]);
    }
  };
  
  return (
    <div className="w-full max-w-2xl mx-auto">
      <div 
        className={cn(
          "border-2 border-dashed rounded-2xl p-8 text-center transition-all duration-300",
          isDragging 
            ? "border-blue-500 bg-blue-50 dark:bg-blue-950/30" 
            : "border-gray-300 dark:border-gray-700 hover:border-blue-400 dark:hover:border-blue-600"
        )}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        onClick={handleClick}
      >
        <input 
          type="file" 
          ref={fileInputRef} 
          accept="image/*" 
          className="hidden" 
          onChange={handleFileInputChange}
        />
        
        <div className="mb-4 text-5xl text-blue-500">
          <i className="fa-solid fa-cloud-upload-alt"></i>
        </div>
        
        <h3 className="text-xl font-semibold mb-2">上传图片进行OCR识别</h3>
        <p className="text-gray-500 dark:text-gray-400 mb-6">
          拖放图片到此处，或<span className="text-blue-500 font-medium">点击上传</span>
        </p>
        
        <p className="text-sm text-gray-400 dark:text-gray-500">
          支持JPG, PNG, WEBP格式，最大5MB
        </p>
      </div>
      
    </div>
  );
}